package huixue.cn.com.rxapp;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.util.List;

import huixue.cn.com.rxapp.base.SimpleActivity;
import huixue.cn.com.rxapp.entity.Book;
import huixue.cn.com.rxapp.service.AIDLService;
import huixue.cn.com.rxapp.service.ServiceC;
import huixue.cn.com.rxapp.util.LogUtils;

public class Main2Activity extends SimpleActivity {

    private BookManager mBookManager;

    @Override
    public int getLayout() {
        return R.layout.activity_main2;
    }

    @Override
    public void initView() {

    }

    @Override
    public void addEvent() {
        Intent intent = new Intent("com.lypeer.aidl");
        intent.setPackage("huixue.cn.com.rxapp");
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }

    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(getLocalClassName(), "service connected");
            Log.e(getLocalClassName(), "service==>:"+service.getClass().getName());

            mBookManager = BookManager.Stub.asInterface(service);

            LogUtils.e("mBookManager==>" + mBookManager.getClass().getName());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(getLocalClassName(), "service disconnected");
        }
    };


    public void addBook(View view) {
        //如果与服务端的连接处于未连接状态，则尝试连接
        /*if (!mBound) {
            attemptToBindService();
            Toast.makeText(this, "当前与服务端处于未连接状态，正在尝试重连，请稍后再试", Toast.LENGTH_SHORT).show();
            return;
        }*/
        if (mBookManager == null) return;

        Book book = new Book();
        book.setName("APP研发录In");
        book.setPrice(30);
        try {
            mBookManager.addBook(book);
            Log.e(getLocalClassName(), book.toString());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void getBook(View view) {
        if (mBookManager == null) return;
        try {
            List list =  mBookManager.getBooks();
            Log.e(getLocalClassName(), list.size()+"");

        }catch (RemoteException e){
            e.printStackTrace();

        }
    }
}
